import { Component } from '@angular/core';
import {
  AlertController, App, IonicPage, LoadingController, NavController, NavParams, Platform,
  ToastController
} from 'ionic-angular';
import { JoinPage } from '../join/join';
import { SignUpPage } from "../sign-up/sign-up";
import { ExercisesPage } from "../exercises/exercises";
import { ResoursePage } from "../resourse/resourse";
import { MessagePage } from "../message/message";
import { AllCoursePage } from "../all-course/all-course";
import { ApiProvider } from "../../providers/api/api";

import { LocalStorProvider } from '../../providers/local-stor/local-stor';
import { UnitListPage } from "../unit-list/unit-list";
import { PersonalCentrePage } from "../personal-centre/personal-centre";
import { TeachingPage } from "../teaching/teaching";
import { UnitSourceListPage } from "../unit-source-list/unit-source-list";
import { MyScoreListPage } from "../my-score-list/my-score-list";
import { JPushService } from "ionic2-jpush";
import { SpeechRecognition } from "@ionic-native/speech-recognition";
import { Location } from "@angular/common";
import { RecordProvider } from "../../providers/record/record";
import { JPush } from "@jiguang-ionic/jpush";
/**
 * Generated class for the MainPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-main',
  templateUrl: 'main.html',
})
export class MainPage {

  unitId;//单元id
  user_id = '';//当前登录的用户id111

  courseList = [];//首页班课列表
  startCourseInfo;//当前正在授课的班课信息

  backFlag = false;//手机原生返回回退键标识

  curClassCourseId = -1;//当前正在授课的班课id

  // 是否存在继续授课时的padding;
  padding = false;

  noMoreFlag = 0;//加载更多标识（0—还有更多；1-没有更多）

  curPage = 1;
  curPageSize = 6;

  constructor(public navCtrl: NavController, public navParams: NavParams, private storage: LocalStorProvider, public http: ApiProvider,
    public loadingCtrl: LoadingController, public platform: Platform, private toastCtrl: ToastController,
    private jPushPlugin: JPushService, public speechRecognition: SpeechRecognition, public appCtrl: App, public location: Location,
    public record: RecordProvider, public jpush: JPush, public alertCtrl: AlertController) {
    this.platform.ready().then(() => {

      /*      this.jpush.init().then(res => {
              // console.log(res);
            })
            this.jpush.getRegistrationID().then(id => {

              // alert(id)

              this.storage.getKey('user_id').then(res => {

                setTimeout(() => {
                  this.jpush.setAlias({
                    sequence: 1,
                    alias: res.toString()
                  }).then(msg => {
                    //alert(JSON.stringify(msg))
                  }, err => {
                    // alert(JSON.stringify(err))
                  })
                }, 5000)

              })

            })



            document.addEventListener("jpush.openNotification", (event) => {

              const confirm = this.alertCtrl.create({
                title: '提示',
                message: '收到新的消息推送，是否查看？',
                buttons: [
                  {
                    text: '不用了',
                    handler: () => {

                    }
                  },
                  {
                    text: '去看看',
                    handler: () => {
                      this.navCtrl.push(MessagePage, { studentId: this.user_id });
                    }
                  }
                ]
              });

              confirm.present();
            }, false)

            document.addEventListener("jpush.receiveNotification", (event) => {

              const confirm = this.alertCtrl.create({
                title: '提示',
                message: '收到新的消息推送，是否查看？',
                buttons: [
                  {
                    text: '不用了',
                    handler: () => {

                    }
                  },
                  {
                    text: '去看看',
                    handler: () => {
                      this.navCtrl.push(MessagePage, { studentId: this.user_id });
                    }
                  }
                ]
              });

              confirm.present();
            }, false)*/

    });
  }

  startRecord() {
    this.record.startRecord();
  }

  /*  /!**
     * 注册极光
     *!/
    init() {
      this.jPushPlugin.init()
        .then(res => {
          alert(res);
          this.jPushPlugin.receiveNotification().subscribe( res => {
            alert('收到')
            console.log(res)
            console.log('收到通知')
          })
        })
        .catch(err => alert(err))
    }

    recievedRegisterId()
    {
      this.jPushPlugin.receiveRegistrationId().subscribe(id=>{
        alert(id);
      });
    }

    /!**
     * 获取ID
     *!/
    getRegistrationID() {
      this.jPushPlugin.getRegistrationID()
        .then(res => {alert(res);alert(1);})
        .catch(err => {alert(err);alert(2)})
    }*/

  showJoin = false;

  ionViewDidLoad() {
    /*    this.storage.getKey("user_id").then(val => {
          this.user_id = val;
          this.getCourseList();
          //this.curStartCourse();
        });

        // this.http.checkVersion("main");
        //
        if (new Date(2018, 6, 26).getTime() < new Date().getTime()) {
          this.showJoin = true;
        }*/

    //this.init();

    /*    this.init();

        this.jPushPlugin.setDebugMode(true);

        this.jPushPlugin.setAlias(this.user_id+'').then(item=>{
          alert(item);
          alert(222222);
        });*/
  }

  ionViewDidEnter() {
    this.storage.getKey("user_id").then(val => {
      this.user_id = val;
      this.getCourseList();
      //this.curStartCourse();
    });
  }

  /**
   * 查看我的成绩
   */
  queryScoreList() {
    if (this.courseList.length == 0) {
      this.http.showToast("你还没有加入任何课程，请先申请加入课程", "bottom");
    }
    else {
      this.navCtrl.push(MyScoreListPage, { student_id: this.user_id });
    }
  }

  /**
   * 加入课程
   */
  joinCourse() {

    this.navCtrl.push(JoinPage);
  }

  /**
   * 签到
   */
  signUp() {
    this.navCtrl.push(SignUpPage);
    // this.navCtrl.push(MySignListPage);
  }

  /**
   * 首页全部习题
   */
  exercises() {
    this.navCtrl.push(ExercisesPage);
  }

  /**
   * 首页全部资源
   */
  resourse() {
    this.navCtrl.push(ResoursePage);
  }

  message() {
    this.navCtrl.push(MessagePage, { studentId: this.user_id });
  }

  /**
   * 首页我的课程列表（新增课程刷新接口没找到？？）
   */
  getCourseList() {
    this.curPage = 1;
    this.http.post("/courseTeacherController/courseListTeacher.do", { userId: +this.user_id, searchName: '', rows: this.curPageSize, page: this.curPage }).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.http.showToast(item["Message"], "bottom");
      }
      else {
        console.log(444);
        console.log(item);
        this.courseList = item["rows"];
        console.log(5454545545)
        console.log(this.courseList)
      }
    })
  }

  /**
   * 跳转进入全部课程列表
   */
  allCourse() {
    this.navCtrl.push(AllCoursePage);
  }

  /**
   * 当前授课课程单位信息
   */
  curStartCourse() {
    this.http.post("/course/getLastestStartCourse.do", { student_id: +this.user_id }).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.http.showToast(item["11111111"], "bottom");
      }
      else {
        this.startCourseInfo = item["LatestCourse"];
        if (item["LatestCourse"] != null) {
          this.curClassCourseId = item["LatestCourse"]["classCourseId"];
        }
      }
    })
  }

  /**
   * 继续听课
   * @param classcourseid
   * @param unitid
   * @constructor
   */
  ContinueCourse(classcourseid, unitid, teacherId) {
    this.navCtrl.push(UnitSourceListPage, {
      classCourseId: classcourseid, teacherId: teacherId, unitId: unitid, studentId: this.user_id,
      classType: "60001", sourceType: 'xt'
    });
  }

  /**
   * 进入单元列表
   * @param classCourseId
   * @param teacherId
   * @param courseName
   * @constructor
   */
  UnitList(classCourseId, teacherId, courseName) {
    this.navCtrl.push(UnitListPage, { classCourseId: classCourseId, teacherId: teacherId, courseName: courseName })
  }

  /**
   * 下拉刷新
   * @param refresher
   */
  async doRefresh(refresher) {
    this.noMoreFlag = 0;
    let loading = this.loadingCtrl.create({
      content: '刷新中...',
      showBackdrop: false
    });
    loading.present();

    this.curPage = 1;
    try {
      this.http.post("/courseTeacherController/courseListTeacher.do", { userId: +this.user_id, searchName: '', rows: this.curPageSize, page: this.curPage }).subscribe(item => {
        if (item["Code"] == "11111111") {
          this.http.showToast(item["Message"], "bottom");
        }
        else {
          setTimeout(() => {
            refresher.complete();
            loading.dismiss();
          }, 2000);

          this.courseList = item["rows"];
        }
      })
      /*let courseList = await this.http.post1("/index/bannerIndex.do", { studentId: +this.user_id, bannerType: 1 });
      let lastestCourse = await this.http.post1("/course/getLastestStartCourse.do", { student_id: +this.user_id });

      this.courseList = courseList["indexCourseList"];
      this.startCourseInfo = lastestCourse["LatestCourse"] == "undefined" ? null : lastestCourse["LatestCourse"];

      if (lastestCourse["LatestCourse"] != null) {
        this.curClassCourseId = lastestCourse["LatestCourse"]["classCourseId"];
      }
      else {
        this.curClassCourseId = -1;
      }

      if (courseList["Code"] == "11111111" || lastestCourse["Code"] == "11111111") {
        this.http.showToast("获取失败", "bottom");
        refresher.complete();
        loading.dismiss();
      }
      else {
        setTimeout(() => {
          refresher.complete();
          loading.dismiss();
        }, 2000);
      }*/
    }
    catch (error) {
      this.http.showToast("获取失败", "bottom");
      refresher.complete();
      loading.dismiss();
    }
  }

  /**
   * 进入个人中心
   */
  personalCentre() {
    this.navCtrl.push(PersonalCentrePage, { courseNum: this.courseList.length });
  }

  /**
   * 进入授课
   */
  Teaching(a, b, c) {
    this.navCtrl.push(TeachingPage, { classCourseId: a, teacherId: b, courseName: c });
  }

  existApp() {
    if (!this.backFlag) {
      this.backFlag = true;
      let toast = this.toastCtrl.create({
        message: '再按一次退出程序',
        duration: 3000,
        position: 'bottom'
      });

      toast.onDidDismiss(() => {
        this.backFlag = false;
      });

      toast.present();
    }
    else {
      this.platform.exitApp();
    }
  }

  ChangeState(e) {
    this.padding = e;//
  }

  /**
   * 加载更多
   * @param infiniteScroll
   */
  doInfinite(infiniteScroll) {
    this.curPage = this.curPage + 1;
    if (this.noMoreFlag == 1) {
      infiniteScroll.complete();
      return;
    }

    this.http.post("/courseTeacherController/courseListTeacher.do", { userId: +this.user_id, searchName: '', rows: this.curPageSize, page: this.curPage }).subscribe(item => {
      if (item["Code"] == "11111111") {
        this.http.showToast(item["Message"], "bottom");
      }
      else {
        if (item["rows"] != null) {
          setTimeout(() => {
            if (item["rows"].length > 0) {
              for (var i = 0; i < item["rows"].length; i++) {
                this.courseList.push(item["rows"][i]);
              }
            }
            else {
              this.noMoreFlag = 1;
            }
            infiniteScroll.complete();   //当数据请求完成调用
          }, 1000);
        }
        else {
          this.noMoreFlag = 1;
          infiniteScroll.complete();   //当数据请求完成调用
        }
      }
    });
  }


  /**
   * 进入单元列表
   * @param classcourseId
   * @param courseId
   * @param operateType
   * @constructor
   */
  ViewUnitList(classcourseId, courseId, operateType, className, classCourseNum, teacherId,courseType,is_startcourse,unitId) {


    localStorage.setItem("unitId",unitId);
    localStorage.setItem("classCourseId",classcourseId);
    localStorage.setItem('classcourse_num',classCourseNum);

    if(courseType=="hot"&&is_startcourse==0){

      this.navCtrl.push(TeachingPage, {classcourseId:classcourseId,unitId:unitId,sta:courseType,is_s:is_startcourse,classcourse_num: classCourseNum});
    }else{
      this.navCtrl.push(UnitListPage, { classCourseId: +classcourseId, courseName: className, courseId: +courseId, operateType: operateType, classcourse_num: classCourseNum, teacherId: teacherId,unitId:unitId,sta:courseType,is_s:is_startcourse});
    }

  }
}
